package cn.doctorpda.conference.ui.common;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import cn.doctorpda.conference.R;
import cn.doctorpda.conference.bean.Msg;
import cn.doctorpda.conference.config.AppConfig;
import cn.doctorpda.conference.event.CollectShareJsInfo;
import cn.doctorpda.conference.event.CollectWebToAppInfo;
import cn.doctorpda.conference.localstore.UserInfo;
import cn.doctorpda.conference.okhttp.https.GetUrl;
import cn.doctorpda.conference.popup.ShareDialog;
import cn.doctorpda.conference.presenter.CollectDeletePresenter;
import cn.doctorpda.conference.presenter.CollectSavePresenter;
import cn.doctorpda.conference.ui.BaseActivity;
import cn.doctorpda.conference.ui.BaseFragment;
import cn.doctorpda.conference.ui.MainActivity;
import cn.doctorpda.conference.utils.JsInterface;
import cn.doctorpda.conference.utils.L;
import cn.doctorpda.conference.utils.StringUtils;
import cn.doctorpda.conference.view.callbackview.IMsgView;
import cn.doctorpda.conference.view.callbackview.IRegisterView;
import okhttp3.Call;

/**
 * Created by huangjinlong on 2016/5/24.
 */
public class DetailFragment extends BaseFragment implements IRegisterView, IMsgView {

    private Toolbar mToolbar;
    public static WebView mWebView;
    private String id;
    private String type;
    private String url;
    private String title;
    private CollectShareJsInfo info = null;
    private CollectSavePresenter savePresenter;
    private CollectDeletePresenter deletePresenter;

    private Menu menu;
    private View xCustomView;
    private FrameLayout webView_fl;
    private WebChromeClient.CustomViewCallback xCustomViewCallback;
    private int flag = -1;


    public static DetailFragment newInstance(String title, String id, String type, String url, int flag) {
        DetailFragment fragment = new DetailFragment();
        Bundle bundle = new Bundle();
        bundle.putString("id", id);
        bundle.putString("type", type);
        bundle.putString("url", url);
        bundle.putString("title", title);
        bundle.putInt("flag", flag);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public String getPageName() {
        return "DetailFragment";
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(false);
        id = getArguments().getString("id");
        type = getArguments().getString("type");
        url = getArguments().getString("url");
        title = getArguments().getString("title");
        flag = getArguments().getInt("flag");
        L.d("flaghehe" + flag);
        EventBus.getDefault().register(this);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_detail, container, false);
        initView(view);
//        view.setOnKeyListener(new View.OnKeyListener() {
//            @Override
//            public boolean onKey(View v, int keyCode, KeyEvent event) {
//                if (event.getAction() == KeyEvent.ACTION_DOWN) {
//                    T.showShort(getContext(),"按了web返回");
//                    if (keyCode == KeyEvent.KEYCODE_BACK) {
//                        L.d("web返回");
//                        if (mWebView.canGoBack()) {
//                            mWebView.goBack();
//                            return true;
//                        }
//                    }
//                }
//                return false;
//            }
//        });

        return view;
    }

    private void initView(View view) {
        mToolbar = (Toolbar) view.findViewById(R.id.title_common);
        mWebView = (WebView) view.findViewById(R.id.webview);
        ((BaseActivity) getActivity()).setSupportActionBar(mToolbar);
        if (!TextUtils.isEmpty(title)) {
            getActivity().setTitle(title);
        } else {
            getActivity().setTitle("详情");
        }
        ActionBar actionBar = ((BaseActivity) getActivity()).getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mWebView.canGoBack()) {
                    mWebView.goBack();// 返回前一个页面
                } else if (flag != -1) {
                    Intent intent = new Intent(getActivity(), MainActivity.class);
                    startActivity(intent);
                    getActivity().finish();
                } else {
                    getActivity().finish();
                }
            }
        });
        webView_fl = (FrameLayout) view.findViewById(R.id.webView_fl);
        String userAgent = mWebView.getSettings().getUserAgentString();
        mWebView.getSettings().setUserAgentString(userAgent + " doctorpda");
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        mWebView.getSettings().setDomStorageEnabled(true);
        mWebView.getSettings().setDatabaseEnabled(true);
        mWebView.getSettings().setAllowFileAccess(true);
        mWebView.getSettings().setPluginState(WebSettings.PluginState.ON);
        mWebView.getSettings().setSupportMultipleWindows(true);
        mWebView.getSettings().setDefaultTextEncodingName("UTF-8");
        mWebView.getSettings().setUseWideViewPort(true);
        mWebView.getSettings().setLoadWithOverviewMode(true);
        if (Build.VERSION.SDK_INT >= 19) {
            mWebView.getSettings().setLoadsImagesAutomatically(true);
        } else {
            mWebView.getSettings().setLoadsImagesAutomatically(false);
        }
        if (Build.VERSION.SDK_INT > 16) {
            mWebView.getSettings().setAllowUniversalAccessFromFileURLs(true);
        }
        mWebView.setScrollContainer(false);
        mWebView.setScrollbarFadingEnabled(false);
        mWebView.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
        mWebView.getSettings().setSupportZoom(false);

        mWebView.getSettings().setAppCacheEnabled(false);
        mWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        mWebView.setHorizontalScrollBarEnabled(false);
        mWebView.setHorizontalScrollbarOverlay(false);


        mWebView.addJavascriptInterface(new JsInterface(getActivity()), "android");
        mWebView.setWebViewClient(new MyWebViewClient());
        mWebView.setWebChromeClient(new MyWebViewChromeClient());
        if (id.equals("QRView")) {
            getActivity().setTitle("医会通现场签到");
        } else {
            if (TextUtils.isEmpty(url)) {
                L.d("轮播图？？" + type + "传过来的id" + id + "传过来的url " + url);
                mWebView.loadUrl("http://www.doctorpda.cn/");
            } else if (!url.contains("http://")) {
                L.d("资讯" + type);
                url = AppConfig.API_URL + "/api/app/doc/form/" + id;//拼接详情页

            }
        }
        if (type.equals("subject") && !TextUtils.isEmpty(url)) {
            url = StringUtils.replaceIndex(url.lastIndexOf("/"), url, "/mindex/");
            L.d("位置" + url.lastIndexOf("/"));
        }


//        T.showShort(getContext(),"资讯" + type + "传过来的id" + id + "传过来的url " + url);
        if (!TextUtils.isEmpty(url)) {
            L.d("连接" + GetUrl.appendClientInfo(url));
            mWebView.loadUrl(GetUrl.appendClientInfo(url));
        }
        savePresenter = new CollectSavePresenter(this);
        deletePresenter = new CollectDeletePresenter(this);

    }


    private class MyWebViewChromeClient extends WebChromeClient {

        private View xprogressvideo;

        // 播放网络视频时全屏会被调用的方法
        @Override
        public void onShowCustomView(View view, CustomViewCallback callback) {
            mToolbar.setVisibility(View.INVISIBLE);
            mWebView.setVisibility(View.INVISIBLE);
            // 如果一个视图已经存在，那么立刻终止并新建一个
            if (xCustomView != null) {
                callback.onCustomViewHidden();
                return;
            }
            webView_fl.addView(view);
            xCustomView = view;
            xCustomViewCallback = callback;
            webView_fl.setVisibility(View.VISIBLE);
        }

        // 视频播放退出全屏会被调用的
        @Override
        public void onHideCustomView() {
            mToolbar.setVisibility(View.VISIBLE);
            if (xCustomView == null)// 不是全屏播放状态
                return;
            xCustomView.setVisibility(View.GONE);
            webView_fl.removeView(xCustomView);
            xCustomView = null;
            webView_fl.setVisibility(View.GONE);
            xCustomViewCallback.onCustomViewHidden();
            mWebView.setVisibility(View.VISIBLE);
        }

        // 视频加载时进程loading
        @Override
        public View getVideoLoadingProgressView() {
//            if (xprogressvideo == null) {
//                LayoutInflater inflater = LayoutInflater
//                        .from(WebViewActivity.this);
//                xprogressvideo = inflater.inflate(
//                        R.layout.video_loading_progress, null);
//            }
            return null;
        }

        // For Android 3.0+
        public void openFileChooser(ValueCallback<Uri> uploadFile) {

        }

        // For Android 3.0+
        public void openFileChooser(ValueCallback uploadFile, String acceptType) {

        }

        //For Android 4.1
        public void openFileChooser(ValueCallback<Uri> uploadFile, String acceptType, String capture) {
        }
    }

    private class MyWebViewClient extends WebViewClient {

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, final String failingUrl) {
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {

            return super.shouldOverrideUrlLoading(view, url);
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);

        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getAppDataForJs(CollectShareJsInfo info) {
        this.info = info;
        L.d("info" + info);
        L.d("UserInfo" + UserInfo.getUserInfo());
        if (info != null) {
            if (UserInfo.getUserInfo() != null) {
                setHasOptionsMenu(true);
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getCollectWebToApp(CollectWebToAppInfo info) {
        if (info.getType().equals("collected")) {
            menu.getItem(0).setTitle("取消收藏");
            this.info.setIsCollected("1");
        } else {
            menu.getItem(0).setTitle("收藏");
            this.info.setIsCollected("0");
        }

    }

    @Override
    public void onDestroyView() {
        mWebView.loadUrl("about:blank");
        mWebView.stopLoading();
        mWebView.setWebChromeClient(null);
        mWebView.setWebViewClient(null);
        mWebView.destroy();
        EventBus.getDefault().unregister(this);
//        isClick = false;
        super.onDestroyView();
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.menu_main, menu);
        this.menu = menu;
        if (info != null) {
            if (info.getIsCollected().equals("0")) {
                menu.getItem(0).setTitle("收藏");
            } else {
                menu.getItem(0).setTitle("取消收藏");
            }
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_collect:
                if (info != null) {
                    if (info.getIsCollected().equals("0")) {
                        savePresenter.getCollect(id, type);
                    } else {
                        deletePresenter.deleteCollect(id, type);
                    }
                }
                break;
            case R.id.action_share:
                if (info != null) {
                    ShareDialog dialog = ShareDialog.newInstance(info.getTitle(), info.getDescription(), info.getUrl(), info.getThumb());
                    dialog.show(getFragmentManager(), "share");
                }
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void setResult(Msg msg) {
        menu.getItem(0).setTitle("取消收藏");
        info.setIsCollected("1");
        try {
            JSONObject object = new JSONObject();
            object.put("type", "collected");
            object.put("data", id);
            mWebView.loadUrl("javascript:to_web_action('" + object.toString() + "')");
        } catch (Exception e) {
            e.printStackTrace();
        }
//        T.showShort(getActivity(), msg.getMsg());
    }

    @Override
    public void setError(Call call, Exception e) {

    }

    @Override
    public void setRegisterView(Msg msg) {
        menu.getItem(0).setTitle("收藏");
        info.setIsCollected("0");
        try {
            JSONObject object = new JSONObject();
            object.put("type", "uncollected");
            object.put("data", id);
            mWebView.loadUrl("javascript:to_web_action('" + object.toString() + "')");
        } catch (Exception e) {
            e.printStackTrace();
        }
//        T.showShort(getActivity(), msg.getMsg());
    }

    @Override
    public void setRegisterError(Call call, Exception e) {

    }
}
